<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomFollow\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomFollow\Contract\RoomFollowContract;
use MoChat\Plugin\RoomTrack\Constants\Event;
use MoChat\Plugin\RoomTrack\Constants\EventName;
use MoChat\Plugin\RoomTrack\Contract\RoomTrackContract;

/**
 * 添加跟进.
 *
 * Class Store
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomFollowContract
     */
    protected $roomFollowService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 互动轨迹表.
     * @Inject
     * @var RoomTrackContract
     */
    private $track;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/roomFollow/store", methods="POST")
     */
    public function handle(): array
    {
        // 接收参数
        $params['roomId'] = (int) $this->request->input('roomId');
        $params['content'] = $this->request->input('content');
        $params['followTemplateId'] = (int) $this->request->input('followTemplateId', 0);
        // 校验参数
        $this->validated($params);

        // 数据操作
        Db::beginTransaction();
        try {
            $data = [
                'corp_id' => user()['corpId'],
                'employee_id' => user()['id'],
                'room_id' => $params['roomId'],
                'follow_template_id' => $params['followTemplateId'],
                'content' => $params['content'],
            ];
            // 添加跟进
            $id = $this->roomFollowService->createRoomFollow($data);
            // 记录轨迹
            $this->recordTrack($params['roomId'], $params['content'], $id, $params['followTemplateId']);
            Db::commit();
            return [$id];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '编辑用户跟进状态失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'roomId' => 'required|integer|min:1|bail',
            'content' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'roomId.required' => '客户群id 必传',
            'content.required' => '跟进内容 必传',
        ];
    }

    /**
     * 记录轨迹.
     */
    private function recordTrack(int $roomId, string $content, int $relationId, int $followTemplateId): void
    {
        $jsonContact = [
            'title' => $followTemplateId > 0 ? EventName::FOLLOW_TEMPLATE : EventName::FOLLOW,
            'content' => $content,
        ];
        $data = [
            'room_id' => $roomId,
            'employee_id' => user()['id'],
            'content' => Json::encode($jsonContact),
            'corp_id' => user()['corpId'],
            'relation_id' => $relationId,
            'event' => $followTemplateId > 0 ? Event::FOLLOW_TEMPLATE : Event::FOLLOW,
        ];

        $res = $this->track->createRoomTrack($data);
        if (! is_int($res)) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '记录轨迹失败');
        }
    }
}
